package com.stephen.data.tree;

/**
 * @author: stephen
 * @create: 2020-02-03 12:56
 * @description: 顺序存储二叉树的遍历
 */
public class ArrayBinaryTreeDemo {

    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7};
        ArrayBinaryTree binaryTree = new ArrayBinaryTree(arr);
        binaryTree.preOrder();
    }
}

class ArrayBinaryTree {

    private int[] arr; // 存储数据节点的数组

    public ArrayBinaryTree(int[] arr) {
        this.arr = arr;
    }

    public void preOrder() {
        this.preOrder(0);
    }

    public void preOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数据为空");
            return;
        }
        // 先输出根节点
        System.out.println(arr[index]);
        // 再向左递归
        if (index * 2 + 1 < arr.length) {
            preOrder(index * 2 + 1);
        }

        // 再向右递归
        if (index * 2 + 2 < arr.length) {
            preOrder(index * 2 + 2);
        }

    }
}


